<?php
namespace Todo\Model\Rate;

use Todo\Model\BaseModel;
use Todo\Service\UserService;

class ImportsModel extends BaseModel
{
    protected $order = 'id DESC';

    public $tableName = 'rate_imports';

    public $_validate = array(
        array('project_id', 'require', '请选择项目'),
        array('norm_id', 'require', '必须选择指标'),
        array('score', 'require', '分数不能为空')
    );
    
    protected $_auto = array(
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    /**
     * 导入一行线下成绩
     * @param int $proId 项目ID
     * @param array $normArr 指标数组
     * @param array $row 数据数组
     * @param int $exists 数据存在处理方式，备用
     * @return bool
     */
    public function importOne($proId, $normArr, $row, $exists){
        if(count($row) < 3 || !$row[0] || !$row[1]){
            $this->error = "姓名、工号（学号）不能为空";
            return false;
        }
        $data = array(
            'project_id' => $proId,
            'tnt_id' => auto_tnt()
        );
        $info = UserService::getInstance()->checkImportUser(trim($row[1]), trim($row[0]));
        if(!$info){
            $this->error = "用户(".$row[0].",".$row[1].")不存在";
            return false;
        }
        $data['user_id'] = $info['user_id'];
        $data['name'] = $info['name'];
        foreach ($normArr as $i => $normId){
            $data['norm_id'] = $normId;
            $old = $this->where($data)->find();
            if($old){
                $old['score'] = $row[$i + 2];
                if($this->save($old) == false) return false;
            }else{
                $data['score'] = $row[$i + 2];
                if($this->add($data) == false) return false;
            }
        }
        return true;
    }

    /**
     * 导出Excel
     * @param $list array 数据列表
     * @param $excel ExcelUtil Excel操作对象
     */
    public function exports($list, $excel){
        $title = array(
            'project'=>'项目',
            'norm'=>'指标',
            'name'=>'姓名',
            'number'=>'工号/学号',
            'score'=>'分数'
        );
        foreach ($list as &$row){
            if($row['project_id']) $row['project'] = D('Todo/Rate/project')->keyFind($row['project_id'], 'title');
            else $row['project'] = '';

            if($row['norm_id']) $row['norm'] = D('Todo/Rate/Norm')->keyFind($row['norm_id'], 'title');
            else $row['norm'] = '';

            $row['number'] = D('Todo/Sys/UserIdentity')->where(array('user_id'=>$row['user_id']))->getField('param');
        }
        $excel->exportExcel("线下分数", $title, $list);
    }
}